package file

import (
	"encoding/json"
	"io/ioutil"
	"net/http"

	"chainmaker.org/chainmaker/smarteditor/event"
	"chainmaker.org/chainmaker/smarteditor/session"
	"chainmaker.org/chainmaker/smarteditor/util"

	"github.com/88250/gulu"
)

// SaveFileHandler handles request of saving file.
func SaveFileHandler(w http.ResponseWriter, r *http.Request) {
	httpSession, _ := session.HTTPSession.Get(r, session.CookieName)
	if httpSession.IsNew {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	uid := httpSession.Values["uid"].(string)

	result := gulu.Ret.NewResult()
	defer gulu.Ret.RetResult(w, r, result)

	var args map[string]interface{}

	if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
		log.Error(err)
		result.Code = -1
		return
	}

	filePath := args["file"].(string)
	sid := args["sid"].(string)

	if gulu.Go.IsAPI(filePath) || util.BelongsGoPath(filePath) {
		result.Code = -1
		result.Msg = "gosrc or gopath or gomod can not be edited"
		return
	}
	if !session.CanAccess(uid, filePath) {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	code := args["code"].(string)
	err := ioutil.WriteFile(filePath, []byte(code), 0644)
	if err != nil {
		log.Error("write code to file failed. err :%v", err)
		result.Code = -1
		wSession := session.WideSessions.Get(sid)
		wSession.EventQueue.Queue <- &event.Event{
			Code: event.EvtCodeServerInternalError,
			Sid:  sid,
			Data: "can't save file " + filePath}
		return
	}
	//session.SendUpdateFileEvent(sid, filePath)
}
